#ifndef LOCKABLE_H
#define LOCKABLE_H

#include <Asm.h>

/**
  A class that implements a spinlock / binary semaphore.
**/
class Lockable
{
public:
  Lockable()
  {
    lock = 0;
  }

  ~Lockable()
  {
  }
  
  void getLock()
  {
    // spin until we get the lock.
    u32int newVal = 1;
    // If we exchange the lock value with 1 and get 1 out, it was locked.
    while (atomicExchange(&lock, newVal) == 1)
    {
      // Do nothing.
    }
    // We got the lock, return.
  }
  
  bool tryLock()
  {
    // Spin once.
    u32int newVal = 1;
    if (atomicExchange(&lock, newVal) == 0)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  
  bool testLock()
  {
    return lock;
  }
  
  void releaseLock()
  {
//     u32int newVal = 0;
//     atomicExchange(&lock, newVal);
    lock = 0;
  }

private:
  /**
    The actual lock variable
  **/
  u32int lock;

};

#endif
